package cn.org.gs.channel;

import org.junit.Test;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.FileChannel;
// 测试文件截取方法turncate(long size)，文件指定长度后的内容将被删除
public class TestChannel {
    public static void main(String[] args) throws Exception{

        // 创建FileChannel
        RandomAccessFile aFile = new RandomAccessFile("d:\\1.txt", "rw");

        FileChannel channel = aFile.getChannel();
        FileChannel truncate = channel.truncate(2);

        // 创建Buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 读取数据到Buffer中
        int bytesRead = truncate.read(buffer);
        while(bytesRead != -1) {
            System.out.println("读取：" + bytesRead);
            buffer.flip(); // 读写模式的转换

            while (buffer.hasRemaining()) {
                System.out.print((char) buffer.get());
            }

            buffer.clear();
            bytesRead = truncate.read(buffer);

        }
        aFile.close();
        System.out.println("读取文件完成！");
    }

    @Test
    public void testBUffer() throws Exception{
        RandomAccessFile aFile = new RandomAccessFile("d:\\1.txt", "rw");

        FileChannel channel = aFile.getChannel();
        ByteBuffer header = ByteBuffer.allocate(1024);
        ByteBuffer body = ByteBuffer.allocate(1024);

        ByteBuffer[] buffers = {header, body};
        System.out.println(channel.read(buffers));
    }
}
